<?php
	function OnlyDigits ($String) {
		$Matches = array ();
		preg_match_all ('( \\d+ )x', $String, $Matches);
		return (implode ('', $Matches [0]));
	}

	function DateReverse ($Date) {
		return (implode ('-', array_reverse (explode ('.', $Date))));
	}

	function PhoneNumberNormalize ($Number) {
		$Number = OnlyDigits ($Number);
		if (strlen ($Number) === 7) return ('7495'.$Number);		
		if (strlen ($Number) === 10) return ('7'.$Number);
		if (strlen ($Number) === 11)
			if ('8' === substr ($Number, 0, 1))
				return ('7'.substr ($Number, 1));
		return ($Number);
	}

	function ParseInvoice ($Filename) {
		global $PG;
		$PREG_DATE = '\\d{2}\\.\\d{2}\\.\\d{4}';
		$Query = $Row = $Matches = array ();
		$InvoiceStart = $InvoiceEnd = $PG_Result = '';
		$InvoiceNumber = $CurrentNumber = 0;
		if (FALSE !== ($Handle = fopen ($Filename, 'r'))) {
			while (FALSE !== ($Line = fgets ($Handle))) {
				if (preg_match ('( 277340426056 \\s / \\s (\\d+) )xm', $Line, $Matches)) {
					$InvoiceNumber = $Matches [1];
					if (pg_fetch_all (pg_query ($PG, 'select * from "Invoices" where "Number" = '.$InvoiceNumber.';'))) return ("PARSER: Invoice $InvoiceNumber already exists.");
				}
				if ($InvoiceNumber and preg_match ("(<td .*? $PREG_DATE <br> .*? <br> .*? <br> .*? ( $PREG_DATE ) .*? ( $PREG_DATE ) <br> .*? $PREG_DATE </td> )xm", $Line, $Matches)) {
					$InvoiceStart = DateReverse ($Matches [1]);
					$InvoiceEnd = DateReverse ($Matches [2]);
					array_push ($Query, "insert into \"Invoices\" values ($InvoiceNumber,'$InvoiceStart','$InvoiceEnd');");
				}
				if ($InvoiceNumber and preg_match ('(<br> [^\\d]+ (\\d{11}) </td>)xm', $Line, $Matches)) {
					$CurrentNumber = $Matches [1];
				}
				if ($InvoiceNumber and $CurrentNumber and ('<tr style="font-weight: normal; font-size: 7pt;">' === trim ($Line))) {
					$Row ['date'] = DateReverse (trim (fgetss ($Handle)));
					$Row ['time'] = trim (fgetss ($Handle));
					$Row ['number'] = trim (fgetss ($Handle));
					$Row ['PS'] = trim (fgetss ($Handle));
					$Row ['VTK'] = trim (fgetss ($Handle));
					$Row ['service'] = trim (fgetss ($Handle));
					fgets ($Handle);
					$Row ['amount'] = trim (fgetss ($Handle));
					$Row ['cost'] = intval (trim (fgetss ($Handle)) * 10000, 10);
					$Outbound = 'TRUE';
					switch ($Row ['service']) {
						case 'Телеф.': case '':
							if ('&lt;--' === substr ($Row ['number'], 0, 6)) {
								$Row ['number'] = substr ($Row ['number'], 6);
								$Outbound = 'FALSE';
							}
							strlen ($Row ['amount']) > 5 || $Row ['amount'] = '00:'.$Row ['amount'];
							array_push ($Query, 'insert into "Calls" values ('.
								$InvoiceNumber.','.
								'\''.$Row ['date'].' '.$Row ['time'].'\','.
								$CurrentNumber.','.
								PhoneNumberNormalize ($Row ['number']).','.
								$Outbound.','.
								'\''.$Row ['amount'].'\','.
								$Row ['cost'].');');
						break;
						case 'sms i':
						case 'sms o':
							$Outbound = ('sms o' === $Row ['service']) ? 'TRUE' : 'FALSE';
							if ('&lt;--' === substr ($Row ['number'], 0, 6)) {
								$Row ['number'] = substr ($Row ['number'], 6);
							}
							array_push ($Query, 'insert into "SMS" values ('.
								$InvoiceNumber.','.
								'\''.$Row ['date'].' '.$Row ['time'].'\','.
								$CurrentNumber.','.
								PhoneNumberNormalize ($Row ['number']).','.
								$Outbound.','.
								$Row ['cost'].');');
						break;
						case 'mms i':
						case 'mms o':
							$Outbound = ('mms o' === $Row ['service']) ? 'TRUE' : 'FALSE';
							if ('&lt;--' === substr ($Row ['number'], 0, 6)) {
								$Row ['number'] = substr ($Row ['number'], 6);
							}
							array_push ($Query, 'insert into "MMS" values ('.
								$InvoiceNumber.','.
								'\''.$Row ['date'].' '.$Row ['time'].'\','.
								$CurrentNumber.','.
								'\''.$Row ['number'].'\','.
								$Outbound.','.
								$Row ['cost'].');');
						break;
						case 'gprs':
							if ('&lt;--' === substr ($Row ['number'], 0, 6)) {
								$Row ['number'] = substr ($Row ['number'], 6);
								$Outbound = 'FALSE';
							}
							$Row ['amount'] = OnlyDigits ($Row ['amount']);
							array_push ($Query, 'insert into "GPRS" values ('.
								$InvoiceNumber.','.
								'\''.$Row ['date'].' '.$Row ['time'].'\','.
								$CurrentNumber.','.
								'\''.$Row ['number'].'\','.
								$Outbound.','.
								$Row ['amount'].','.
								$Row ['cost'].');');
						break;
#						case 'ussd':
#						break;
#						case 'cw':
#						break;
#						case 'ch':
#						break;
#						case 'cfu':
#						break;
#						case 'cf a':
#						break;
					}
				}
			}
			fclose ($Handle);
			if (FALSE === ($PG_Result = @pg_query ($PG, implode ($Query)))) return ('PARSER: DB: '.pg_last_error ());
		} else return ('PARSER: Error while opening file.');

		$TC = $TS = $TM = $TG = $TT = 0;

		$TC = pg_fetch_all (pg_query ($PG, 'select count (*) as "Total" from "Calls" where "Invoice" = '.$InvoiceNumber.';'));
		$TC = $TC [0]['Total'];
		$TS = pg_fetch_all (pg_query ($PG, 'select count (*) as "Total" from "SMS" where "Invoice" = '.$InvoiceNumber.';'));
		$TS = $TS [0]['Total'];
		$TM = pg_fetch_all (pg_query ($PG, 'select count (*) as "Total" from "MMS" where "Invoice" = '.$InvoiceNumber.';'));
		$TM = $TM [0]['Total'];
		$TG = pg_fetch_all (pg_query ($PG, 'select count (*) as "Total" from "GPRS" where "Invoice" = '.$InvoiceNumber.';'));
		$TG = $TG [0]['Total'];
		$TT = $TC + $TS + $TM + $TG;

		return ("PARSER: Invoice file parsed successfully: $TC voice, $TS SMS, $TM MMS, $TG GPRS (total $TT) lines.");
	}
?>